package top.lcm889.oj.offer.按数据结构分类.链表;

/**
 * @author Coder-lcm
 * @date 2021/2/5
 */
public class T206_反转链表 {
    //使用递归，反转链表
    public static ListNode reverseList1(ListNode head) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode next = head.next;
        ListNode newHead = reverseList(next);
        next.next = head;
        head.next = null;
        return newHead;
    }

    //使用头插法，反转链表
    public static ListNode reverseList(ListNode head) {
        ListNode newList = new ListNode(-1);
        while (head != null) {
            ListNode next = head.next;
            head.next = newList.next;
            newList.next = head;
            head = next;
        }
        return newList.next;
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(345);
        listNode.next = new ListNode(231);
        listNode.next.next = new ListNode(313);
        ListNode newListNode = reverseList(listNode);
        System.out.println(newListNode.val);
    }
}

